package com.sundog.sundroid;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

/**
 * Represents the waiting screen for standard users
 * 
 * @author Matt
 *
 */
public class Wait extends Activity implements OnClickListener {
	
	/** Delay between messages */
	private static final int DELAY = 5000;
	/** Story ID */
	public static int storyID;
	/** Boolean to stop executing */
	private boolean execute = true;
	/** Create a packet filter to receive messages from a specific user */
	PacketFilter filter = new PacketTypeFilter(Message.class);
	/** Boolean to determine if a message has been received from the moderator */
	private boolean messageReceived = false;
	/** Connection configuration for XMPP messaging */
	private final ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 80, "jabber.org"); 
	/** Establishes XMPP connection using the connection configuration */
	private final XMPPConnection connection = new XMPPConnection(connConfig);
	
	/** Create a packet listener to process messages */
	PacketListener myListener = new PacketListener() {
	
		/** Method for processing incoming packets */
		public void processPacket(Packet packet) {
				
			Message msg = (Message) packet;	
			Log.d("***", "User received message: " + msg.getBody() + " from " + msg.getFrom());
			
			// Process message based on whether or not it contains an "Admin" tag
			if(!msg.getBody().startsWith("Admin")) {
				
				execute = false;
				connection.disconnect();
				Log.d("***", "User disconnected");
				startGame();
				storyID = Integer.parseInt(msg.getBody());
				Log.d("storyid checking", " = " + storyID);
				
			} else {
				messageReceived = true;
			}
	}};
	
	/** Thread for sending messages to moderator every DELAY milliseconds */
	private final Thread t = new Thread() {
		/** Run method of the thread */
        public void run() {
        	// Establish connection to XMPP server
        	connectToServer();
        	// Wait for 5 seconds
        	try {
        		Thread.sleep(DELAY);
        	}
        	catch(Exception e) {
        		e.printStackTrace();
        	}
        	
        	// Continue executing thread until admin chooses next story
        	while(execute) {
        		// Send message to admin every 5 seconds until admin replies
        		while(!messageReceived) {
        			try {
        				sendMessageToModerator();
        				Thread.sleep(DELAY);
        			} catch(Exception e) {
        				Log.d("EXCEPTION", e.getMessage());
        			}
        		}
        	}
        }
    };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.waiting);
		
		// Set up click listener for cancel button
        View cancelButton = this.findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(this);

        // Start executing the messaging thread
       	t.start();
	}
	
	/**
	 * Set up the event handler for the cancel button 
	 */
	public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.cancel_button:
    		messageReceived = true;
    		connection.disconnect();
    		this.finish();
    		break;
    	}
	}

	/**
	 * Start the game after receiving message from the moderator
	 */
    private void startGame() {
    	messageReceived = true;
    	String[] storyNames = Login.storyNames;
    	Intent i = new Intent(this, UserScreen.class);
		i.putExtra("SID", Login.id);
		i.putExtra("username", Login.user);

    	startActivity(i);
    }
    
    /**
     * Connect to the XMPP server and add the packet listener to the connection
     */
    public void connectToServer() {
    	try {
    		Log.d("***", "User Connect...");
    		connection.connect();
    		connection.login(Login.user,Login.pass);
    		Log.d("***", "User Connected ");
    	} catch (XMPPException e) {
    		Log.d("***", "XMPPException");
    	}
		connection.addPacketListener(myListener, filter);
    }
	
	/**
	 * Connect to the Jabber server and send a message to the moderator of the game
	 */
	private void sendMessageToModerator() {

        // Print out connection information
		Log.d("***", "User Host =" + connConfig.getHost());
		Log.d("***", "User Service Name =" + connConfig.getServiceName());
		Log.d("***", "User Security Mode =" + connConfig.getSecurityMode());

		try {	
			// Connect to the server if not already connected and log in with user name and password from previous activity
			if(!connection.isConnected()) {
				
				Log.d("***", "User Connect...");
				connection.connect();
				connection.login(Login.user,Login.pass);
				Log.d("***", "User Connected");
			}
		} catch (XMPPException e) {
			Log.d("***", "XMPPException");
		}
		
		// Add a packet listener to the connection. The parameters were created above
		connection.addPacketListener(myListener, filter);
		
		// Create a new message, set the message properties, and send the message
		Message message = new Message();
		message.setType(Message.Type.headline);
		message.setTo(Login.usersNames[0]);
		message.setBody("UserConnected");
	    connection.sendPacket(message);
	    Log.d("***", "User sent message");
	}
}